const { createClient } = require("redis");
const fs = require("fs").promises;
const path = require("path");

class RedisDataGenerator {

    constructor(redisHost = "127.0.0.1", redisPort = 6379, redisDb = 0) {
        this.redisHost = redisHost;
        this.redisPort = redisPort;
        this.redisDb = redisDb;
    }

    async load(jsonFilePath, redisKey) {
        try {
            // 读取文件内容
            const data = await fs.readFile(path.resolve(jsonFilePath), "utf8");
            const parsedData = JSON.parse(data);

            // 创建 Redis 客户端并连接
            const client = createClient({
                url: `redis://${this.redisHost}:${this.redisPort}/${this.redisDb}`
            });
            await client.connect();

            // 在插入新数据前删除现有 key
            await client.del(redisKey);
            console.log(`已删除 Redis key: ${redisKey}`);

            // 根据数据类型选择存储方式
            if (Array.isArray(parsedData)) {
                // 数组类型数据存储为 Redis List
                await Promise.all(parsedData.map(item => 
                    client.rPush(redisKey, JSON.stringify(item))
                ));
                console.log(`成功将 ${parsedData.length} 个元素存入 Redis List`);
            } else if (typeof parsedData === "object" && parsedData !== null) {
                // 对象类型数据存储为 Redis String
                await client.set(redisKey, JSON.stringify(parsedData));
                console.log(`成功将对象存入 Redis String`);
            } else {
                throw new Error("JSON 数据类型不支持，必须是数组或对象");
            }

            // 关闭 Redis 连接
            await client.quit();
        } catch (error) {
            console.error("加载数据到 Redis 时出错:", error.message);
            throw error;
        }
    }
}

module.exports = RedisDataGenerator;